package com.ruoyi.web.controller.tool;

import com.fazecast.jSerialComm.SerialPort;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

public class JSerialCommReader {
    public static void main(String[] args) {
        SerialPort serialPort = SerialPort.getCommPort("COM3");
        serialPort.openPort();
        serialPort.setBaudRate(115200);
        serialPort.setNumDataBits(8);
        serialPort.setNumStopBits(1);
        serialPort.setParity(SerialPort.NO_PARITY);

        InputStream input = serialPort.getInputStream();

        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                try {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
                    Date date = new Date(System.currentTimeMillis());
                    Scanner scanner = new Scanner(input);
                    while (scanner.hasNextLine()) {
                        String line = scanner.nextLine();
                        System.out.println("串口发送： " + line + "  " + formatter.format(date));
                    }
                } catch (Exception e) {
                    System.err.println("从串口读取失败:" + e.getMessage());
                }
            }
        };

        // 每隔1秒执行一次任务
        timer.scheduleAtFixedRate(task, 0, 1000);

        // 运行后请记得在合适的地方关闭串口连接，例如在应用程序退出时
        // serialPort.closePort();
    }
}
